package com.pignest.hotel.ui.member;

import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.Datebox;
import org.zkoss.zul.Label;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Window;

import com.pignest.framework.util.Utils;
import com.pignest.hotel.beans.Card;
import com.pignest.hotel.beans.Member;
import com.pignest.hotel.beans.MemberLevel;
import com.pignest.hotel.beans.Memberchargehistrory;
import com.pignest.hotel.definition.ChargeOpType;
import com.pignest.hotel.definition.MemberState;
import com.pignest.hotel.definition.PayMethod;
import com.pignest.hotel.service.MemberService;
import com.pignest.hotel.spring.Services;
import com.pignest.hotel.system.Hotel;
import com.pignest.hotel.system.L;
import com.pignest.hotel.util.UIUtils;

/**
 * 会员新增与修改管理
 */
public class AddMemberWindow extends Window implements EventListener {

	private static final long serialVersionUID = 1521087887829897950L;
	private MemberService service;
	private boolean success;
	
	private Textbox nameField;		//会员姓名
	private Listbox sexListbox;		//性别
	private Textbox mobileField;	//手机
	private Listbox certificateTypeListbox;//证件类型
	private Textbox certificateNoField;	//证件号
	private Textbox mailField;		//邮件
	private Textbox streetField;	//街道;
	private Datebox birthdayField;
	
	private Listbox memberLevelListbox;//会员级别如金卡、银卡、普通
	private Label canSelfLivingLabel;
	private Label canSelfQuitLabel;
	private Label cardPriceLabel;
	private Label leastChargeLabel;
	private Label overdrawLabel;
	
	private Textbox chargePrice;
	private Label totalPayed;
	private Textbox cardNoField;
	private Listbox chargeTypeListbox;
	
//	private Button submitbtn;

	public AddMemberWindow() {
		service = Services.getMemberService();
		addEventListener("onCreate", this);
	}
	
	@Override
	public void onEvent(Event event) throws Exception {
		if ("onCreate".equals(event.getName())) {
			nameField=(Textbox)getFellow("nameField");
			sexListbox=(Listbox)getFellow("sexListbox");
			mobileField=(Textbox)getFellow("mobileField");
			certificateTypeListbox=(Listbox)getFellow("certificateTypeListbox");
			certificateNoField=(Textbox)getFellow("certificateNoField");
			mailField=(Textbox)getFellow("mailField");
			streetField=(Textbox)getFellow("streetField");
			birthdayField=(Datebox)getFellow("birthdayField");
			
			memberLevelListbox = (Listbox)getFellow("memberLevelListbox");
			canSelfLivingLabel = (Label)getFellow("canSelfLivingLabel");
			canSelfQuitLabel = (Label)getFellow("canSelfQuitLabel");
			cardPriceLabel = (Label)getFellow("cardPriceLabel");
			leastChargeLabel = (Label)getFellow("leastChargeLabel");
			overdrawLabel = (Label)getFellow("overdrawLabel");
			
			chargePrice=(Textbox)getFellow("chargePrice");
			cardNoField=(Textbox)getFellow("cardNoField");
			totalPayed =(Label)getFellow("totalPayed");
			chargeTypeListbox=(Listbox)getFellow("chargeTypeListbox");
			
//			submitbtn=(Button)getFellow("submitbtn");
			changeLevelTip();
			
			chargePrice.addEventListener(Events.ON_CHANGE, new EventListener() {
				@Override
				public void onEvent(Event event) throws Exception {
					int t = Utils.toPrice(cardPriceLabel.getValue()) + Utils.toPrice(chargePrice.getValue());
					totalPayed.setValue(Utils.toPrice(t));
				}
			});
		}
	}
	
	public String save() {
		if (!Hotel.onDuty()) {
			return "你当前不在值班状态, 无法新增会员.";
		}
		String name = nameField.getValue();
		if (StringUtils.isEmpty(name) || name.length() > 30) {
			return "用户名必填, 且在30字符以内";
		}
		String gender = UIUtils.getSelectedValue(sexListbox);
		String phone = mobileField.getValue();
		String ctype = UIUtils.getSelectedValue(certificateTypeListbox);
		String cid = certificateNoField.getValue();		//XXX 身份证验证		CheckUtil.validatePersonalId(value)
		if (StringUtils.isEmpty(cid)) {
			return "证件号码必填";
		}
		String email = mailField.getValue();
		String address = streetField.getValue();
		Date birthday = birthdayField.getValue();
		
		String id = UIUtils.getSelectedValue(memberLevelListbox);
		MemberLevel level = service.getMemberLevel(id);
		if (level == null)
			return "请选择一会员等级";
		final int chargePrice = Utils.toPrice(this.chargePrice.getValue());
		if (chargePrice < level.getLevelPrice()) {
			return "会员等级:" + level.getMemberlevel() + " 需要至少充值: " + Utils.toPrice(level.getLevelPrice());
		}
		
		String cardNumber = StringUtils.defaultIfEmpty(cardNoField.getValue(), null);
//		if (StringUtils.isEmpty(cardNumber))
//			return "请一张空卡做为会员卡";
		final Card card = cardNumber == null ? null : Services.getCardService().getCardByCardNumber(cardNumber);
		if (cardNumber != null) {
			if (card == null)
				return "此卡片未在系统中录入";
			if (!card.isEnable())
				return "此卡片已经被禁用";
			if (!card.isUsable())
				return "此卡片已经被使用, 或者未设置卡号";
		}
		
		final int cardPrice = level.getLevelPay();
		final PayMethod method = PayMethod.valueOf((String)UIUtils.getSelectedValue(chargeTypeListbox));
		
		final Member m = new Member();
		m.setName(name);
		m.setSex(gender);
		m.setMobile(phone);
		m.setCertificatType(ctype);
		m.setCertificateNo(cid);
		m.setMail(email);
		m.setStreet(address);
		m.setBirthday(birthday);
		
		m.setMemberLevel(level);
		m.setBalance(chargePrice);
		m.setCardNo(cardNumber);
		m.setDealTime(new Date());
		m.setState(MemberState.OnUsed.name());
		
		service.executeInTransaction(new Runnable() {
			@Override
			public void run() {
				service.insert(m);
				int allprice =cardPrice + chargePrice;
				if (card != null)
					Services.getCardService().grantCard(card, m);
				Hotel.receive(allprice, ChargeOpType.OnCharge, method, "新增会员: " + m.getName() + ", 卡金和充值" );
				if (cardPrice > 0) {
					Hotel.receive(cardPrice, ChargeOpType.OnConsume, PayMethod.MEMBER_CARD, "收卡本金:" + m.getName());
				}
				if (chargePrice > 0) {
					Memberchargehistrory ch = new Memberchargehistrory();
					ch.setMember(m);
					ch.setChargeTime(new Date());
					ch.setChargetype(PayMethod.CASH.name());
					ch.setPrice(chargePrice);
					ch.setOptype(ChargeOpType.OnCharge.name());
					ch.setRemark("办理会员卡时充值"+Utils.toPrice(chargePrice));
					service.insert(ch);
				}
				if(cardPrice>0){
					Memberchargehistrory ch = new Memberchargehistrory();
					ch.setMember(m);
					ch.setChargeTime(new Date());
					ch.setChargetype(PayMethod.CASH.name());
					ch.setPrice(-cardPrice);
					ch.setOptype(ChargeOpType.OnConsume.name());
					ch.setRemark("办理会员卡时购卡"+Utils.toPrice(cardPrice));
					service.insert(ch);
				}
				L.insert(m);
			}
		});
		
		success = true;
		return null;
	}

	public void changeLevelTip() {
		String id = UIUtils.getSelectedValue(memberLevelListbox);
		MemberLevel level = service.getMemberLevel(id);
//		this.level = level;

		cardPriceLabel.setValue(Utils.toPrice(level.getLevelPay()));
		canSelfLivingLabel.setValue(level.getSelfhelplive());
		canSelfQuitLabel.setValue(level.getSelfhelpout());
		cardPriceLabel.setValue(Utils.toPrice(level.getLevelPay()));
		leastChargeLabel.setValue(Utils.toPrice(level.getLevelPrice()));
		overdrawLabel.setValue(Utils.toPrice(level.getOverdraft()));
		
		chargePrice.setValue(Utils.toPrice(level.getLevelPrice()));
		totalPayed.setValue(Utils.toPrice(level.getLevelPrice() + level.getLevelPay()));
	}
	
	public void onReadCard(String serial) {
		if (serial == null) {
			return;
		}
		Card card = Services.getCardService().getCardBySerialNumber(serial);
		if (card == null) {
			UIUtils.alert("该卡片未在系统中登记, 无法使用");
			return;
		}
		if (!card.isUsable()) {
			if (StringUtils.isEmpty(card.getCardNumber())){
				UIUtils.alert("该卡片无法使用, 卡号未设置");
				return;
			}
			UIUtils.alert("该卡片无法使用, 可能已经在使用中(" + card.getHolderName2() + ")");
			return;
		}
		cardNoField.setValue(card.getCardNumber());
	}
	
	public boolean isSuccess() {
		return success;
	}

//	public String getoPratorId() {
//		return oPratorId;
//	}
//
//	public void setoPratorId(String oPratorId) {
//		this.oPratorId = oPratorId;
//	}


    
}
